import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';

/**
 * 异常接管，统一异常返回数据
 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Status http参数文档
 */
@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger('GlobalExceptionFilter');
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    // this.logger.log('Error occurred: ' + exception);
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    response.header('Content-Type', 'application/json; charset=utf-8');
    const result = new ResponseDto(
      exception.response.status || exception.response.statusCode || 200,
      exception.response.data || [],
      exception.response.message || '请求成功',
    );
    response.status(status).send(result);
  }
}
export class ResponseDto<T> {
  readonly data: T;

  @ApiProperty()
  readonly code: number;

  @ApiProperty()
  readonly message: string;

  constructor(code: number, data?: any, message = 'success') {
    this.code = code;
    this.data = data;
    this.message = message;
  }

  static success(data?: any) {
    return new ResponseDto(200, data);
  }
}
